package com.popo.thread;

import java.util.LinkedList;

public class ThreadTest {

	public static void main(String[] args) {

		final Loop loop = new Loop();
		ThreadLocal tl = new ThreadLocal(null);

		tl.start();
		new Thread() {
			public void run() {
				System.out.println("LoopThread:+"+getId()+","+getName());
				loop.Looper();
			};
		}.start();
		int a=0;
		while (true) {
			synchronized (loop.queue) {
				Message msg = new Message();
				msg.t = tl.w;
				msg.msg=a+++",";
				loop.queue.enQueue(msg);
			}
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
}

class Loop {
	public MessageQueue queue = null;

	Loop() {
		queue = new MessageQueue();
	}

	public void Looper() {
		while (true) {
			synchronized (queue) {
				Message msg = queue.get();
				if (msg != null) {
					msg.t.p(msg.msg);
				}
			}

		}
	}
}

class ThreadLocal extends Thread {
	public W w = new W() {

		@Override
		public void p(String s) {
			// TODO Auto-generated method stub
			System.out.println(getId()+","+getName() + "+"+s);
		}

	};

	public ThreadLocal(W w) {
		super();
		System.out.println("ThreadLocal:"+getId()+","+getName());
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();
	}
}

class MessageQueue {
	LinkedList<Message> queue;

	public MessageQueue() {
		super();
		queue = new LinkedList<Message>();
	}

	public boolean enQueue(Message str) {
		synchronized (queue) {
			return queue.add(str);
		}
		
	}

	public Message get() {
		synchronized (queue) {
			if (!queue.isEmpty()) {
				
					return queue.pop();
				
			} else {
				return null;
			}
		}
	}

}

class Message {
	String msg;
	W t;
}

interface W {
	public void p(String s);
}
